package org.easy.tool.common;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Valley
 * Created by Valley on 2023/10/24 10:02
 */
public class EasyResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream out;
    private ServletOutputStream filterOutput;

    public EasyResponseWrapper(HttpServletResponse response) {
        super(response);
        out = new ByteArrayOutputStream();
    }

    /**
     * 巧妙将ServletOutputStream放到公共变量，解决不能多次读写问题
     */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (filterOutput == null) {
            filterOutput = new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    out.write(b);
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setWriteListener(WriteListener writeListener) {
                }
            };
        }
        return filterOutput;
    }

    ////使用示例
    //EasyResponseWrapper wrapper = new EasyResponseWrapper(res);
    //chain.doFilter(req, wrapper);
    //String resData= new String(wrapper.toByteArray(), res.getCharacterEncoding());
    //res.setContentType("application/json;charset=utf-8");
    ////将buffer重置，因为我们要重新写入流进去
    //res.resetBuffer();
    //res.setContentLength(resData.getBytes().length);
    //res.getOutputStream().write(resData.getBytes());
    public byte[] toByteArray() {
        return out.toByteArray();
    }


}
